/*
 * @Author: 黄栋 核心js库
 * @Date: 2020-03-12 10:53:23 
 * @Last Modified by: 黄栋
 * @Last Modified time: 2020-03-17 21:35:59
 */


let rootPath = "https://www.empirise.com/mall/public/index.php/";
// const rootPath = "/api/";

var basePath = rootPath;
const navigator = weex.requireModule("navigator");
var bsessionid = ""

var asCore = {

	rootPath: basePath,
	bsessionid: bsessionid,
	/* 自动登录代码 */
	autoLogin: function (callback) {
		const progress = weex.requireModule('progress');
		var s = this;
		/* 判断当前是否记住了密码，没有记住密码那只能跳出登录界面自行登录 */
		var pref = weex.requireModule("storage")
		pref.getItem("as_username", event => {
			var username = event.data;
			if (event.result != "success") {
				if (weex.config.bundleUrl.indexOf("login/login.js") == -1) {
					navigator.push("root:app/login/login.js");
				}
				return false
			}
			pref.getItem("as_password", res => {
				if (res.result != "success") {
					if (weex.config.bundleUrl.indexOf("login/login.js") == -1) {
						navigator.push("root:app/login/login.js");
					}
					return false
				}
				var ps = res.data;
				//progress.showFull("自动登录中...");
				/* 自动登录 */
				var stream = weex.requireModule("stream");

				stream.fetch({
					method: "POST",
					url: basePath + "web/login/index",
					type: "json",
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
					},

					body: s.toParams({
						account: username,
						password: ps
					})
				},
					ret => {
						if (!ret.ok) {
							if (weex.config.bundleUrl.indexOf("login/login.js") == -1) {
								navigator.push("root:app/login/login.js");
							}
						} else {
							var re = ret.data;
							if (re.code == "200") {
								//progress.dismiss();
								if (re.token) {
									pref.setItem('userToken', re.token);
									//设置失效时间--5天失效
									var dd = new Date();
									dd.setDate(dd.getDate() + 4);
									let timeOver = dd.getTime();
									pref.setItem('timeOver', timeOver);

								}
								s.setBsessionid(re.data.users_uuid);
								if (callback) callback();
							} else {
								// s.toast("自动登录失败,请重新登录");
								//progress.dismiss();
								if (weex.config.bundleUrl.indexOf("login/login.js") == -1) {
									navigator.push("root:app/login/login.js");
								}
							}
						}
					}
				);
			});
		});
	},
	/* 设置用户信息 */
	setContext: function (value) {
		var pref = weex.requireModule("storage")
		value = value ? JSON.stringify(value) : '';
		pref.setItem('context', value);
	},
	/* 获取用户信息 */
	getContext: function (callback) {
		var pref = weex.requireModule("storage")
		pref.getItem('context', event => {
			var value = event.data;
			try {
				value = JSON.parse(value);
			} catch (error) {
				value = {};
			}
			if (callback) callback(value);
		});
	},

	setAddressList: function (value) {
		var pref = weex.requireModule("storage")
		value = value ? JSON.stringify(value) : '';
		pref.setItem('addressList', value);
	},
	getAddressList: function (callback) {
		var pref = weex.requireModule("storage")
		pref.getItem('addressList', event => {
			var value = event.data;
			if (event.result != "success") {
				value = "";
			}
			if (callback) callback(value);
		});
	},
	setBsessionid: function (value) {
		var pref = weex.requireModule("storage")
		pref.setItem('users_id', value);
	},
	getBsessionid: function (callback) {
		var pref = weex.requireModule("storage")
		pref.getItem('users_id', event => {
			var value = event.data;
			if (event.result != "success") {
				value = "";
			}
			if (callback) callback(value);
		});
	},
	getTime: function (callback) {
		var pref = weex.requireModule("storage")
		pref.getItem('imgtime', event => {
			if (event.result == "success") {
				var value = event.data;
				if (callback) callback(value);
			} else {
				if (callback) callback("10000");
			}
		});
	},
	setTime: function (time) {
		var pref = weex.requireModule("storage")
		pref.setItem('imgtime', time);
	},
	/* 与web端的ajax用法一致 */
	post: function (action, param, callBack) {
		let that = this;
		var stream = weex.requireModule("stream");
		var pref = weex.requireModule("storage");
		var log = weex.requireModule('log')
		let token = "";
		let users_id = "";

		pref.getItem('userToken', event => {
			if (event.result == "success") {
				token = event.data;
			}
			pref.getItem('users_id', eveat => {
				if (eveat.result == "success") {
					users_id = eveat.data;
				}
				var net = weex.requireModule('net');

				net.post(basePath + action, param, {
					'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
					'token': token,
					'users_id': users_id
				}, () => {

				}, (data) => {

					if (data.res.code && data.res.code == 1001) {
						// var navigator = weex.requireModule("navigator");
						// if (weex.config.bundleUrl.indexOf("login/login.js") == -1) {
						// 	navigator.push("root:app/login/login.js");
						// }
						pref.getItem('tokenOver', eveat => {
							if (eveat.result == "success" && eveat.data == '1') {
								// this.alert(data.res.message)
							}
						})
						pref.setItem('tokenOver', 2);

						return false
					}
					pref.setItem('tokenOver', '1');
					if (data.res.token) {
						pref.setItem('userToken', data.res.token);
						//设置失效时间--5天失效
						var dd = new Date();
						dd.setDate(dd.getDate() + 4);
						let timeOver = dd.getTime();
						pref.setItem('timeOver', timeOver);

					}
					// log.log({
					// 	msg: "接口：" + action + "****请求**** 参数" + JSON.stringify(param),
					// 	level: 'error'
					// })
					if (callBack) callBack(data.res, 1);
				}, (data) => {

				}, (data) => {
					log.log({
						msg: "接口：" + action + "****请求**** 参数" + JSON.stringify(param),
						level: 'error'
					})

					log.log({
						msg: "接口：" + action + "****请求**** 返回" + JSON.stringify(data),
						level: 'error'
					})

					// that.toast("Server error");

					if (callBack) callBack("", 0);
				});
				// stream.fetch({
				// 	method: "POST",
				// 	url: basePath + action,
				// 	type: "json",
				// 	timeout: 30000,
				// 	headers: {
				// 		'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
				// 		'token': token,
				// 		'usersid': users_id
				// 	},
				// 	body: that.toParams(param)
				// },
				// 	function (ret) {
				// 		// that.toast(ret);  
				// 		if (!ret.ok) {
				// 			log.log({
				// 				msg: "接口：" + basePath + action + "****异常**** 参数" + JSON.stringify(param),
				// 				level: 'error'
				// 			})
				// 			if (ret.status == 500) {
				// 				that.toast("Server error");
				// 				// if (callBack) callBack(ret.statusText, false);
				// 			} else if (ret.status == 550) {
				// 				// if (callBack) callBack("timeout", false);
				// 				that.toast("request timeout");
				// 			} else {
				// 				// if (ret.status == -1) {
				// 				// 	that.toast('网络连接失败,请检查网络设置');
				// 				// } 
				// 				that.toast(ret.statusText);
				// 			}
				// 			if (callBack) callBack(ret.statusText, ret.ok);
				// 		} else {
				// 			var data = ret.data;
				// 			if (data.code == 1001) {
				// 				var naviga = weex.requireModule("navigator");
				// 				naviga.push("root:app/login/login.js");
				// 				return false
				// 			}
				// 			log.log({
				// 				msg: "接口：" + action + "****完成**** 参数" + JSON.stringify(param),
				// 				level: 'warn'
				// 			})
				// 			if (data.token) {
				// 				pref.setItem('userToken', data.token);
				// 				//设置失效时间--5天失效
				// 				var dd = new Date();
				// 				dd.setDate(dd.getDate() + 4);
				// 				let timeOver = dd.getTime();
				// 				pref.setItem('timeOver', timeOver);

				// 			}
				// 			try {
				// 				if (callBack) callBack(data, ret.ok);
				// 			} catch (e) {

				// 			}
				// 		}
				// 	});
			});
		});

	},

	/* 解析URL */
	rendUrl: function (url, callback) {
		var s = this;
		s.getBsessionid(bs => {
			if (url.indexOf("bsessionid=") == -1) {
				if (url.indexOf("?") > -1) {
					url += "&as_call_type=ajax&bsessionid=" + bs;
				} else {
					url += "?as_call_type=ajax&bsessionid=" + bs;
				}
			}
			if (callback) callback(basePath + url);
		});
	},
	logout: function (callback) {
		var pref = weex.requireModule("storage")
		this.post("/as/logout", {}, function (data) {
			pref.removeItem("bsessionid");
			if (callback) callback(data);
		});
	},
	toParams: function (obj) {
		var param = ""
		for (const name in obj) {
			if (typeof obj[name] != 'function') {
				param += "&" + name + "=" + encodeURI(obj[name])
			}
		}
		return param.substring(1)
	},
	toast: function (msg) {
		var modal = weex.requireModule("modal");
		modal.toast({
			message: msg
		});
	},
	alert: function (msg) {
		var modal = weex.requireModule("modal");
		modal.alert({
			message: msg
		});
	}

};
export default asCore;
